package metu.tespit.session.semester;

import java.util.List;
import java.util.Map;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.faces.FacesMessages;

import metu.tespit.entity.semester.Semester;
import metu.tespit.session.EntityManager.ExtendedEntityHome;

/**
 
 * @created May 20, 2012
 */
@Name("semesterHome")
public class SemesterHome extends ExtendedEntityHome<Semester>{

	@In(create=true)
	private FacesMessages facesMessages;
	
	@In private Map<String, String> messages;
	
	@In(create=true)
	private SemesterList semesterList;
	
	
	public Long getSemesterId() {
		return (Long) getId();
	}

	public void setSemesterId(Long semesterId) {
		setId(semesterId);
	}

	
	
	@Override
	public String persist() {
        if (!isValid()) {
            return "fault";
        }

        return super.persist();
	}

    @Override
    public String update() {
        if (!isValid()) {
            return "fault";
        }

        return super.update();    //To change body of overridden methods use File | Settings | File Templates.
    }

    private boolean isValid() {
        if (!validateDates())
            return false;

        if (!validateNoExistingSemester()) {
            return false;
        }
        return true;
    }

    private boolean validateDates() {
        if(this.instance.getEndDate().before(this.instance.getStartDate())){
            facesMessages.addFromResourceBundle(messages.get("EndDateBeforeStart"));
            return false;
        }
        return true;
    }

    private boolean validateNoExistingSemester() {

        String dateCriteria = "s.startDate <= :endDate and s.endDate >= :startDate " +
                " and " +
                " ((s.startDate >= :startDate and s.endDate <= :endDate)" +
                " or (s.startDate <= :startDate and s.endDate >= :endDate)" +
                " or (s.startDate >= :startDate and s.endDate >= :endDate)" +
                " or (s.startDate <= :startDate and s.endDate <= :endDate))";

        List<Semester> existingSemesters = getEntityManager().createQuery("from Semester s where " + dateCriteria)
                .setParameter("startDate", this.instance.getStartDate())
                .setParameter("endDate", this.instance.getEndDate())
                .getResultList();
        if (existingSemesters == null || existingSemesters.size() == 0) {
            return true;
        }

        //kendisini sayma
        if (existingSemesters.size() == 1 && existingSemesters.get(0).getId().equals(this.instance.getId())) {
            return true;
        }

        facesMessages.addFromResourceBundle(messages.get("ThereIsATermMakeItBigger"));
        return false;
    }


}
